package com.sen.mqtt.config;

import com.sen.mqtt.domain.MqttConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * 向指定主题发送消息 的配置
 *
 * @作者 韩宗森
 * @创建时间 2025年01月22日 17:29
 */
@Configuration
public class MqttOutboundConfiguration {

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    @Autowired
    private MqttPahoClientFactory pahoClientFactory;

    // 消息通道
    @Bean
    public MessageChannel mqttOutputChannel() {
        return new DirectChannel();
    }

    // 消息出栈处理
    @Bean
    @ServiceActivator(inputChannel = "mqttOutputChannel")
    public MessageHandler mqttOutboundMassageHandler() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttConfigurationProperties.getUrl(),
                mqttConfigurationProperties.getPubClientId(),
                pahoClientFactory);
        messageHandler.setAsync(true); // 异步消息发送
        messageHandler.setDefaultQos(0);
        messageHandler.setDefaultTopic("default"); // 主题名称
        return messageHandler;
    }
}
